package com.example.common.security;

import com.example.common.constant.ResultCode;
import com.example.common.exception.ServiceException;
import com.example.domain.entity.Menu;
import com.example.domain.entity.Role;
import com.example.domain.entity.User;
import com.example.mapper.MenuMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new ServiceException(ResultCode.USER_NOT_FOUND);
        }

        // 查询用户角色
        List<Long> roleIds = userMapper.selectUserRoleIds(user.getId());
        List<Role> roles = roleMapper.selectBatchIds(roleIds);
        user.setRoleIds(roleIds);
        user.setRoles(roles);
        List<String> roleCodes = roles.stream()
                .map(Role::getCode)
                .collect(Collectors.toList());

        // 查询用户菜单权限
        List<Menu> menus = menuMapper.selectMenusByUserId(user.getId());
        List<String> permissions = menuMapper.selectPermissionsByUserId(user.getId());

        // 转换为 UserDetails 对象
        return new UserDetailsImpl(
            user,
            roleCodes,
            permissions,
            menus
        );
    }
}